﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common;

namespace Business
{
    public partial class UserRole
    {
        public Common.ERROR_CODE.ERROR_CODE_ITEMS_UPDATE UpdateUserRole(ref string MessageSystemError, int UserID, List<Business.Role> ListRole)
        {
            DataClassesDataContext context = null;
            try
            {
                context = new DataClassesDataContext(Common.Global.GetConnectionInfo().ConnectionStringSQL);
                //Xóa role cũ
                var query1 = from item in context.UserRoles
                             where item.UserID == UserID
                             select item;
                context.UserRoles.DeleteAllOnSubmit(query1);
                context.SubmitChanges();

                //Cập nhật role mới
                List<Business.UserRole> listUserRole = new List<Business.UserRole>();
                foreach (Role role in ListRole)
                {
                    Business.UserRole userRole = new Business.UserRole();
                    userRole.UserID = UserID;
                    userRole.RoleID = role.RoleID;
                    listUserRole.Add(userRole);
                }
                context.UserRoles.InsertAllOnSubmit(listUserRole);
                context.SubmitChanges();
                return Common.ERROR_CODE.ERROR_CODE_ITEMS_UPDATE.SUCCESS;
            }
            catch(Exception ex)
            {
                MessageSystemError = Common.ExceptionUtils.ExceptionToMessage(ex);
                return Common.ERROR_CODE.ERROR_CODE_ITEMS_UPDATE.SYSTEM_ERROR;
            }
            finally
            {
                context = null;
            }
        }
    }
}
